package com.example.smartcity_poverty.ui.AllService.SmartBus.adapter

import android.app.AlertDialog
import android.view.View
import androidx.fragment.app.Fragment
import com.example.smartcity_poverty.App.Companion.getToken
import com.example.smartcity_poverty.Base.BaseRecyclerAdapter
import com.example.smartcity_poverty.logic.Repository.api
import com.example.smartcity_poverty.logic.Repository.coroutine
import com.example.smartcity_poverty.logic.ServiceBean.SmartBus.BusPersonListModel
import com.example.smartcity_poverty.logic.util.Util.show
import kotlinx.android.synthetic.main.re_bus_person_list.*
import kotlinx.coroutines.Dispatchers
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

/**
 *  created by ikun
 *  ANDROID STUDIO - version 4.0
 *  email: jinkunwei41@gmail.com
 * --------------------------------
 *
 **/
class PersonBusAdapter (
    val fr: Fragment,
    val list: MutableList<BusPersonListModel.RowsBean>,
    layoutId: Int
) : BaseRecyclerAdapter<BusPersonListModel.RowsBean>(list, layoutId){
    override fun setData(
        view: BaseViewHolder.ViewFind,
        data: BusPersonListModel.RowsBean,
        position: Int,
        holder: BaseViewHolder
    ) {
        val d = list[position]
        val fv = holder.viewFind
        val con = holder.viewFind.view?.context

        // 填充数据
        fv.personListTvStart.text = d.start
        fv.personListTvEnd.text = d.end
        fv.personListQIAn.text = "票价: ${d.price}元"
        fv.personListNumber.text = "订单怕编号: ${d.orderNum}"
        fv.personListTime.text = "乘车日期: ${d.createTime}"
        if (d.status.toString() == "0"){
            fv.personListOk.visibility = View.VISIBLE
            fv.personListIsOk.text = "支付"
        }

        // 支付订单
        fv.personListOk.setOnClickListener {
            AlertDialog.Builder(con).apply {
                setTitle("提示")
                setMessage("确定要支付！")
                setPositiveButton("支付"){ _, _ ->
                    coroutine(Dispatchers.Main){
                        api.getBusPostList(getToken(), JSONObject().apply {
                            put("orderNum", d.orderNum.toString())
                            put("paymentType", "电子支付")
                        }.toString().toRequestBody("application/json".toMediaTypeOrNull())).apply {
                            if (this.code == "200"){
                                fv.activity?.runOnUiThread {
                                    this.msg.show()
                                }
                            }else fr.activity?.runOnUiThread { this.msg.show() }
                        }
                    }
                }
                setNegativeButton("取消"){_, _ ->

                }
                show()
            }

        }
    }
}